package com.exam.aspects.logs;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author jly
 * @Since 2017-2-7
 * @Describe
 *
 * 日志信息切面,主要用于记录日志信息
 *
 */

@Aspect
public class LoggerAspect {
    private static Logger logger = LoggerFactory.getLogger(LoggerAspect.class);

    /**
     * 对所有控制层以及服务层方法加上日志,并捕捉异常
     *
     * @author jly
     * @since 2017-2-7
     * */
    @Around("com.exam.aspects.points.ControllerPoint.allPublicMethod()")
    public Object beforeController(ProceedingJoinPoint proceedingJoinPoint){
        long currentTime = System.currentTimeMillis();
        Object returnValue = null;
        logger.info("{}方法执行",proceedingJoinPoint.getSignature());
        printArgsArray(proceedingJoinPoint);
        try {
            returnValue = proceedingJoinPoint.proceed();
            logger.info("共计消耗了  {}  毫秒",System.currentTimeMillis() - currentTime);
            logger.info("{}方法执行完成",proceedingJoinPoint.getSignature());
            return returnValue;
        }catch (Throwable e){
            logger.error("{} 方法执行过程中发生了错误",proceedingJoinPoint.getSignature());
            logger.error("{}", e.getMessage());
        }
        return null;
    }

    private void printArgsArray(ProceedingJoinPoint proceedingJoinPoint) {
        Object[] args = proceedingJoinPoint.getArgs();
        StringBuffer stringBuffer = new StringBuffer("参数信息为:(");
        for (Object arg : args){
            stringBuffer.append(arg);
            stringBuffer.append(",");
        }
        stringBuffer.append(")");
        logger.info(stringBuffer.toString());
    }


    @Around( "com.exam.aspects.points.ServicePoints.allPublicMethod()")
    public Object beforeService(ProceedingJoinPoint proceedingJoinPoint){
        try {
            return proceedingJoinPoint.proceed();
        }catch (Throwable e){

            logger.error(proceedingJoinPoint.getSignature().toString());
            logger.error(proceedingJoinPoint.getSignature() + "方法执行发生了错误");
            logger.error("{}",e.getCause());
        }
        return null;
    }

}
